import requests
from bs4 import BeautifulSoup
import json

headers = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Type": "application/json;charset=UTF-8",
    "Origin": "https://www.servicebio.cn",
    "Referer": "https://www.servicebio.cn/",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-site",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
    "sec-ch-ua": '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
}


def search_product(procode: str) -> list | None:
    """根据产品编码搜索产品

    Args:
        procode (_type_): 商品货号

    Returns:
        _type_: 商品列表
    """
    url = (
        "https://www.servicebio.cn:5666/servicebio-shop-uapi/online/togoods/searchGoods"
    )
    search_config = {
        "titleCate": procode,
        "limit": 99999,
        "userId": None,
    }

    # 定义三种搜索模式
    search_modes = ["HC", "SJ", "YQ"]

    for mode in search_modes:
        search_config["goodsCate"] = mode
        data = json.dumps(search_config, separators=(",", ":"))
        response = requests.post(url, headers=headers, data=data)
        result = response.json()

        if result["data"]["totalCount"] != 0:
            return result["data"]["list"]

    return None  # 如果所有模式都没有找到结果，返回None


def judgment_price(json_data: dict) -> str:
    """判断价格是否大于 60 元，并生成 sku_list

    Args:
        price (str): 价格
    """

    pro_id = json_data["details"]["id"]
    sku_list = json_data["skus"][str(pro_id)]

    _temp_sku = []
    for index, sku in enumerate(sku_list):
        # if sku["mainId"] == pro_id and sku["skuPrice"] > 60:
        if sku["mainId"] == pro_id:
            _temp_sku.append(
                {"price": sku["skuPrice"], "spec": sku["skuDesc"], "index": index + 1}
            )

    return _temp_sku


def get_product_page(product_id: str) -> dict:
    """获取商品详情信息
    商品名称，图片，详情，sku_list

    Args:
        product_id (str): 商品id

    Returns:
        BeautifulSoup: 商品详情页
    """
    url = "https://www.servicebio.cn:5666/servicebio-shop-uapi/online/togoods/details"
    data = {
        "id": product_id,
        "userId": "",
        "onShelfFlag": 1,
        "specificationId": "",
        "specificationGroupId": "",
    }
    data = json.dumps(data, separators=(",", ":"))
    response = requests.post(url, headers=headers, data=data).json()["data"]
    sku_list = judgment_price(response)

    if sku_list:
        json_list = json.loads(response["details"]["imgContent"])
        _temp_img = [
            item["imgContent"]
            for item in json_list
            if "imgContent" in item and item["imgContent"] != ""
        ]
        return {
            "code": response["details"]["itemno"],
            "name": response["details"]["title"],
            "desc": response["details"]["introduceDetail"],
            "photos": _temp_img,
            "skuInfos": sku_list,
        }
    else:
        return None
